package com.cloud.gatewaySpringSecurity.handler;

import com.cloud.gatewaySpringSecurity.pojo.SystemAuthority;
import com.cloud.gatewaySpringSecurity.pojo.WorkUser;
import com.cloud.gatewaySpringSecurity.service.PowerService;
import com.cloud.gatewaySpringSecurity.service.WorkUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author zhozixiong
 * @date 2023/03/02
 *
 * 密码登录验证器
 */
@Primary
@Component
public class PasswordAuthenticationManager implements ReactiveAuthenticationManager {

    @Autowired
    private WorkUserService workUserService;

    @Autowired
    private PowerService powerService;

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        UsernamePasswordAuthenticationToken usernamePasswordToken = (UsernamePasswordAuthenticationToken) authentication;
        if (usernamePasswordToken.getCredentials() == "" || usernamePasswordToken.getPrincipal() == "") {
            throw new AuthenticationServiceException("账号或密码不能为空");
        }
        WorkUser workUser = workUserService.selectWorkByUid((String) usernamePasswordToken.getPrincipal());
        if (workUser == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
//        if (!MD5Util.MD5equals((String) usernamePasswordToken.getCredentials(), workUser.getUpassward())) {
//            throw new BadCredentialsException("密码错误");
//        }
        //查询权限
        List<SystemAuthority> authorityList = powerService.selectPowerByUid((String) usernamePasswordToken.getPrincipal());
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(workUser.getUid(), workUser.getRname(), authorityList);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        return Mono.just(usernamePasswordAuthenticationToken);
    }
}
